package com.github.tommas.admintpl.config;

import com.github.tommas.admintpl.mybatis.ContextInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

@Configuration
public class MybatisConfiguration {
    private static final String CONTEXT_PARAM_VARIABLE = "contextParam";
    private static final String DEFAULT_CONTEXT_PARAM = "context";

    @Bean
    Interceptor[] plugins(MybatisProperties properties) {
        org.apache.ibatis.session.Configuration configuration = properties.getConfiguration();
        Properties vars = configuration.getVariables();
        if (vars.contains(CONTEXT_PARAM_VARIABLE)) {
            throw new RuntimeException("Context param variable already set");
        }

        vars.put(CONTEXT_PARAM_VARIABLE, DEFAULT_CONTEXT_PARAM);

        return new Interceptor[]{
                new ContextInterceptor(),
        };
    }
}
